﻿using System;
using System.IO;
using System.Net;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace RESTAgent.Text
{
	public class PlainTextFormatter : MediaTypeFormatter
	{
		public PlainTextFormatter()
		{
			SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
		}


        protected override bool CanReadType(Type type)
        {
            return type == typeof(string);
        }
        protected override bool CanWriteType(Type type)
        {
            return type == typeof(string);
        }

        protected override Task<object> OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
        {
            return new TaskFactory<object>().StartNew(() =>
            {
                using (var reader = new StreamReader(stream))
                {
                    return reader.ReadToEnd();
                }
            });
        }

        protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
        {
            return new TaskFactory().StartNew(() =>
            {
                var writer = new StreamWriter(stream);
                writer.Write((string)value);
            });
        }

		
	}
}
